﻿using System.Collections.Generic;

namespace BaseDao
{
    public class SingleCache
    {
        private SingleCache() { }

        private static SingleCache _SingleCache = null;
        private static object _lock = new object();

        /// <summary>
        /// 获取实例
        /// </summary>
        /// <returns></returns>
        public static SingleCache GetInstance()
        {
            if (_SingleCache == null) lock (_lock) if (_SingleCache == null)
                        _SingleCache = new SingleCache();

            return _SingleCache;
        }

        private Dictionary<string, object> _Name2Single = new Dictionary<string, object>();

        /// <summary>
        /// 获取单例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetSingle<T>()
        {
            string key = typeof(T).FullName;
            if (!_Name2Single.ContainsKey(key)) lock (this) if (!_Name2Single.ContainsKey(key))
                        _Name2Single[key] = TypeHelper.CreateInstance<T>();

            return (T)_Name2Single[key];
        }
    }
}